package br.ufrj.xml.model.persistence.dao.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import br.ufrj.xml.model.persistence.dao.DocumentDAO;
import br.ufrj.xml.model.persistence.entity.DocumentVO;
import br.ufrj.xml.model.persistence.entity.SchemaVO;

public class DocumentJdbcDAO extends GenericJdbcDAO<DocumentVO> implements DocumentDAO {

	public static final String BASIC_QUERY = "";
	
    public DocumentJdbcDAO(Connection connection) {
    	super(connection);
    }
    
    public List<DocumentVO> findByName(String nmSchema) {
		// TODO Auto-generated method stub
		return null;
	}

	public int count() {
		// TODO Auto-generated method stub
		return 0;
	}

	public void create(DocumentVO entity) {
		String esquema = entity.getSchema().getName();
		String nmTabela = esquema + "." + entity.NM_TABELA;
		nmTabela = nmTabela.replace( SchemaVO.PARAM_NM_SCHEMA , esquema);
		abstractInsert(entity, "INSERT INTO " + nmTabela.toUpperCase() + " (" + entity.COLUNA_NM_RAIZ + ") VALUES (?)",
				new Object[]{ entity.getRaiz() },
				new int[]{ Types.VARCHAR });
	}

	public DocumentVO createAndRegenerateKey(DocumentVO entity) {
		
		String esquema = entity.getSchema().getName();
		String nmTabela = entity.NM_TABELA.replace( SchemaVO.PARAM_NM_SCHEMA , esquema);
		String nmColumnPk = nmTabela + "_PKID";
		nmTabela = esquema + "." + nmTabela;

		abstractInsert(entity, "INSERT INTO " + nmTabela.toUpperCase() + " (" + entity.COLUNA_NM_RAIZ + ") VALUES (?)",
				new Object[]{ entity.getRaiz() },
				new int[]{ Types.VARCHAR });
		
		String sqlMax = "SELECT MAX( " + nmColumnPk.toUpperCase() + " ) FROM " + nmTabela.toUpperCase();
	
		String sql = "SELECT " + nmColumnPk.toUpperCase() + " , " + entity.COLUNA_NM_RAIZ + " " +
					 "FROM " + nmTabela.toUpperCase() + " WHERE " + nmColumnPk.toUpperCase() + " = ( " + sqlMax + " )";
		
		List<DocumentVO> lista = query(sql);
		return lista.get(0);
	}

	public void delete(Integer id) {
		// TODO Auto-generated method stub
		
	}

	public List<DocumentVO> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	public List<DocumentVO> findPageByPage(int firstResult, int maxResults) {
		// TODO Auto-generated method stub
		return null;
	}

	public DocumentVO read(Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	public void update(DocumentVO entity) {
		// TODO Auto-generated method stub
		
	}

	public DocumentVO mapRow(ResultSet resultSet) throws SQLException {
		int i = 1;
		DocumentVO documentVO = new DocumentVO();
		documentVO.setDocumentId(resultSet.getLong(i++));
		documentVO.setRaiz(resultSet.getString(i++));
		return documentVO;
	}


}
